package com.pureut.quality.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.quality.domain.QualityInspectionDocument;
import com.pureut.quality.domain.QualityInventoryRecheck;
import com.pureut.quality.domain.QualityTemporary;
import com.pureut.quality.domain.dto.*;
import com.pureut.quality.domain.vo.MaterialNumberAndBatchNoVo;
import com.pureut.quality.domain.vo.QualityInspectionDocumentVo;
import com.pureut.quality.domain.vo.QualityInventoryRecheckVo;
import com.pureut.quality.mapper.QualityInspectionDocumentMapper;
import com.pureut.quality.mapper.QualityInventoryRecheckMapper;
import com.pureut.quality.mapper.QualityTemporaryMapper;
import com.pureut.quality.service.QualityInspectionDocumentService;
import com.pureut.quality.service.QualityInventoryRecheckService;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.WmsStockInfoVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 库存复检实现层
 * Author:C
 * Date:2023/02/09 11:34
 * @DESC
 */
@Service
public class QualityInventoryRecheckServiceImpl extends ServiceImpl<QualityInventoryRecheckMapper, QualityInventoryRecheck> implements QualityInventoryRecheckService {

    @Resource
    QualityInventoryRecheckMapper qualityInventoryRecheckMapper;

    @Resource
    QualityInspectionDocumentService qualityInspectionDocumentService;

    @Resource
    QualityInspectionDocumentMapper qualityInspectionDocumentMapper;

    @Resource
    QualityTemporaryMapper qualityTemporaryMapper;

    @Resource
    FeignService feignService;

    @Resource
    StorageFegin storageFegin;

    /**
     * 库存复检列表
     *
     * @param qualityInventoryRecheckVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<QualityInventoryRecheckDto> getRecheckList(QualityInventoryRecheckVo qualityInventoryRecheckVo) {
        //状态
        List<SysDictData> recheckStatusArray = DictUtils.getDictCache("quality_inventory_recheck_status");
        Map<String, String> recheckStatusMap = recheckStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<QualityInventoryRecheckDto> list = qualityInventoryRecheckMapper.getList(qualityInventoryRecheckVo);
        for (QualityInventoryRecheckDto entity : list) {
            //状态
            entity.setStatusDict(recheckStatusMap.get(entity.getStatus()));
        }
        return list;
    }

    /**
     * 库存复检新增
     *
     * @param qualityInventoryRecheckVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(QualityInventoryRecheckVo qualityInventoryRecheckVo) throws Exception {
        //保存库存复检单据
        QualityInventoryRecheck qualityInventoryRecheck = new QualityInventoryRecheck();
        String authorityCoding = feignService.getAuthorityCoding("quality:inspecmanage:reinspect:list");
        if (authorityCoding == null) {
            throw new GlobalException("该单据未进行配置，无法生成单据编码");
        }
        qualityInventoryRecheck.setReInspectionSheetNo(authorityCoding)
                .setStatus(1)
                .setMaterialCode(qualityInventoryRecheckVo.getMaterialCode())
                .setMaterialNum(qualityInventoryRecheckVo.getMaterialNumberAndBatchNo().size())
                .setCreateBy(SecurityUtils.getUsername())
                .setCreateTime(new Date())
                .setDeptId(SecurityUtils.getDeptId())
                .setItemRank(qualityInventoryRecheckVo.getItemRank())
                .setCategory(qualityInventoryRecheckVo.getCategory())
                .setMaterialNumber(qualityInventoryRecheckVo.getMaterialNumberAndBatchNo().get(0).getMaterialNumber());
        save(qualityInventoryRecheck);
        //生成检验单据
        QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();

        qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(qualityInventoryRecheckVo.getMaterialNumberAndBatchNo());
        qualityInspectionDocumentVo.setItemRank(qualityInventoryRecheckVo.getItemRank());
        qualityInspectionDocumentVo.setMaterialCode(qualityInventoryRecheckVo.getMaterialCode());
        qualityInspectionDocumentVo.setCategory(qualityInventoryRecheckVo.getCategory());
        qualityInspectionDocumentVo.setMaterialCategory(qualityInventoryRecheckVo.getMaterialCategory());
        qualityInspectionDocumentVo.setBatchNo(qualityInventoryRecheckVo.getMaterialNumberAndBatchNo().get(0).getBatchNo());
        qualityInspectionDocumentVo.setAssociatedNo(qualityInventoryRecheck.getReInspectionSheetNo());
        if (qualityInventoryRecheckVo.getMaterialNumberAndBatchNo().get(0).getWsiCustomCode() == null) {
            qualityInspectionDocumentVo.setDifferentString(qualityInventoryRecheckVo.getMaterialNumberAndBatchNo().get(0).getWsiSupplierCode());
        } else {
            qualityInspectionDocumentVo.setDifferentString(qualityInventoryRecheckVo.getMaterialNumberAndBatchNo().get(0).getWsiCustomCode());
        }
        boolean add = qualityInspectionDocumentService.add(qualityInspectionDocumentVo);
        //如果新增检验单据成功
        if (add) {
            QualityInspectionDocument qualityInspectionDocument = qualityInspectionDocumentMapper.selectOne(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getAssociatedNo, qualityInventoryRecheck.getReInspectionSheetNo()));
            qualityInventoryRecheck.setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo());
            updateById(qualityInventoryRecheck);
            //修改库存中的物料状态为复检
            WmsStockInfoVo wmsStockInfoVo = new WmsStockInfoVo();

            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = qualityInventoryRecheckVo.getMaterialNumberAndBatchNo();
            List<String> materialNumbers = new ArrayList<>();
            for (MaterialNumberAndBatchNoVo entity : materialNumberAndBatchNo) {
                materialNumbers.add(entity.getMaterialNumber());
            }
            wmsStockInfoVo.setMaterialNumberList(materialNumbers);
            wmsStockInfoVo.setWsiMaterialStatus(6);
            storageFegin.updateStatus(wmsStockInfoVo);
        }
        return add;
    }

    /**
     * 撤销
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean revoke(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QualityInventoryRecheck> qualityInventoryRechecks = qualityInventoryRecheckMapper.selectList(new QueryWrapper<QualityInventoryRecheck>().lambda().in(QualityInventoryRecheck::getId, idList));
        //修改库存中的物料状态为在库
        WmsStockInfoVo wmsStockInfoVo = new WmsStockInfoVo();

        List<String> materialNumbers = new ArrayList<>();
        for (QualityInventoryRecheck entity : qualityInventoryRechecks) {
            materialNumbers.add(entity.getMaterialNumber());
        }
        wmsStockInfoVo.setMaterialNumberList(materialNumbers);
        wmsStockInfoVo.setWsiMaterialStatus(2);
        storageFegin.updateStatus(wmsStockInfoVo);

        for (QualityInventoryRecheck entity : qualityInventoryRechecks) {
            if (entity.getStatus() == 1) {
                //同步修改检验单据中的状态
                QualityInspectionDocument qualityInspectionDocument = qualityInspectionDocumentMapper.selectOne(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getInspectionSheetNo, entity.getInspectionSheetNo()));
                qualityInspectionDocument.setStatus(8);
                qualityInspectionDocumentService.updateById(qualityInspectionDocument);
                //修改库存复检单据状态
                entity.setStatus(7);
                entity.setRevokeBy(SecurityUtils.getUsername());
                entity.setRevokeTime(new Date());
            } else {
                throw new GlobalException("只能撤消状态为“待检验”状态的单据");
            }
        }
        return updateBatchById(qualityInventoryRechecks);
    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public QualityInventoryRecheckViewDto getView(Long id) {

        QualityInventoryRecheckViewDto qualityInventoryRecheckViewDto = new QualityInventoryRecheckViewDto();

        QualityInventoryRecheck qualityInventoryRecheck = getById(id);

        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //类别
        List<SysDictData> categoryArray = DictUtils.getDictCache("quality_category");
        Map<String, String> categoryMap = categoryArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //检测阶别
        qualityInventoryRecheckViewDto.setItemRank(String.valueOf(qualityInventoryRecheck.getItemRank()));
        qualityInventoryRecheckViewDto.setItemRankDict(rankMap.get(String.valueOf(qualityInventoryRecheck.getItemRank())));
        //复检单号
        qualityInventoryRecheckViewDto.setReInspectionSheetNo(qualityInventoryRecheck.getReInspectionSheetNo());

        //类别
        qualityInventoryRecheckViewDto.setCategory(String.valueOf(qualityInventoryRecheck.getCategory()));
        qualityInventoryRecheckViewDto.setCategoryDict(categoryMap.get(String.valueOf(qualityInventoryRecheck.getCategory())));
        //物料编码
        qualityInventoryRecheckViewDto.setMaterialCode(qualityInventoryRecheck.getMaterialCode());

        List<WmsStockInfoDto> materialList = new ArrayList<>();

        //根据品质检验单获取物料信息
        List<QualityTemporary> qualityTemporaryList = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, qualityInventoryRecheck.getInspectionSheetNo()));
        StringBuilder stringBuilder = new StringBuilder();

        for (QualityTemporary entity : qualityTemporaryList) {
            stringBuilder.append(entity.getMaterialNumber()).append(",");
        }
        StringBuilder stringBuilder1 = stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        String materialNumber = stringBuilder1.toString();
        AjaxResult data = storageFegin.getDataByCategoryAndCode(materialNumber);
        List<WmsStockInfoDto> data1 = JSON.parseArray(JSON.toJSONString(data.get("data")), WmsStockInfoDto.class);
//        materialList.add(data1);
        qualityInventoryRecheckViewDto.setMaterialList(data1);

        return qualityInventoryRecheckViewDto;
    }
}
